#ifndef CountingSemaphore_h
#include "CountingSemaphore.h"

CountingSemaphore::CountingSemaphore(int init)
{
	m_s1 = new Mutex();
	m_s2 = new Mutex();

	m_s2->lock((Thread*)NULL); //init to 0

	m_value = init;
	m_wait = 0;
	m_wake = 0;
}

CountingSemaphore::~CountingSemaphore(void)
{
	delete m_s1;
	delete m_s2;
}

int CountingSemaphore::up(Thread* t)
{
	m_s1->lock(t);
	m_value++;
	if(m_value <= 0)
	{
		m_wake++;
		if(m_wake == 1)
			m_s2->unlock();
	}
	return m_s1->unlock();
}

int CountingSemaphore::down(Thread *t)
{
	m_s1->lock(t);
	m_value--;
	if(m_value < 0)
	{
		m_s1->unlock();
		m_s2->lock(t);
		m_s1->lock(t);
		m_wake--;
		if(m_wake > 0)
			m_s2->unlock();
	}
	return m_s1->unlock();
}

#endif
